const { query } = require("../utils/db");

// 检查用户权限
exports.checkPermission = (permissionCode) => {
  return async (req, res, next) => {
    try {
      const FUserId = req.user.userId;
      // 1. 检查用户角色是否拥有该权限
      const [roleResult] = await query(
        `SELECT COUNT(*) as count 
         FROM t_user_roles ur
         JOIN t_role_permissions rp ON ur.FRoleId = rp.FRoleId
         JOIN t_permissions p ON rp.FPermissionId = p.FId
         WHERE ur.FUserId = ? AND p.FCode = ?`,
        [FUserId, permissionCode]
      );

      if (roleResult.count === 0) {
        return res.status(403).json({
          code: 403,
          message: "无权访问",
          data: null,
        });
      }

      next();
    } catch (err) {
      next(err);
    }
  };
};
